<?php

namespace app\modules\user\controllers;

use app\common\controllers\CorsController;
use app\common\services\CodeService;
use app\config\Constants;
use app\modules\user\forms\login\MobileLoginForm;
use app\modules\user\forms\login\WechatLoginForm;
use yii\base\UserException;

class LoginController extends CorsController
{
    //微信登陆
    public function actionWechat()
    {
        $form = new WechatLoginForm();
        if($form->load(\Yii::$app->getRequest()->post(),'') && $form->login()){
            $expire = time() + \Yii::$app->params['token_expire'];
            return [
                'expire'=>$expire,
                'token'=>(string)\Yii::$app->jwt->getBuilder()
                    ->expiresAt($expire) //设置token过期时间
                    ->withClaim('uid',$form->getUser()->user_id) //设置Payload数据
                    ->withClaim("credential",Constants::USER)
                    ->getToken(\Yii::$app->jwt->getSigner("HS256"),\Yii::$app->jwt->getKey())
            ];
        }else{
            throw new UserException($form->getFirstFieldError());
        }
    }

    //手机号登陆
    public function actionMobile(){
        $form = new MobileLoginForm();
        if($form->load(\Yii::$app->getRequest()->post(),'') && $form->login()){
            $expire = time() + \Yii::$app->params['token_expire'];
            return [
                'expire'=>$expire,
                'token'=>(string)\Yii::$app->jwt->getBuilder()
                    ->expiresAt($expire) //设置token过期时间
                    ->withClaim('uid',$form->getUser()->user_id) //设置Payload数据
                    ->withClaim("credential",Constants::USER)
                    ->getToken(\Yii::$app->jwt->getSigner("HS256"),\Yii::$app->jwt->getKey())
            ];
        }else{
            throw new UserException($form->getFirstFieldError());
        }
    }

    //发送手机验证码
    public function actionMobileCode($mobile){
        if(CodeService::sendMobileCode($mobile)){
            return "";
        }else{
            throw new UserException(CodeService::getError());
        }
    }
}
